package com.qqhf.hitfood.service.pro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.kevinsawicki.http.HttpRequest;
import com.qqhf.common.config.AppConfiguration;
import com.qqhf.common.utils.Maps;
import com.qqhf.hitfood.bean.entity.PosCity;
import com.qqhf.hitfood.service.IPosCityService;
import org.nutz.json.Json;
import org.nutz.mapl.Mapl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 腾讯地图位置服务
 */
@Service
public class PositionService {

    private Logger logger = LoggerFactory.getLogger(PositionService.class);
    @Autowired
    private AppConfiguration appConfiguration;
    @Autowired
    private IPosCityService posCityService;
    //@Autowired
    //private MongoRepository mongoRepository;

    /**
     * 根据ip获取城市信息
     */
    //@Cacheable(value = Cache.APPLICATION, key = "#root.targetClass.simpleName+':position:'+#ip")
    public PosCity getPostion(String ip) {
        logger.info("根据ip:{}获取城市信息", ip);
        Map<String, String> map = Maps.newHashMap();
        map.put("ip", ip);
        map.put("key", appConfiguration.getTencentKey());
        Map result = null;
        try {
            String str = HttpRequest.get(appConfiguration.getQqApiUrl() + "location/v1/ip", map, true).body();
            result = (Map) Json.fromJson(str);
        } catch (Exception e) {
            System.out.println("获取地理位置异常" + e);
            logger.error("获取地理位置异常", e);
        }
        if (result == null || Integer.valueOf(result.get("status").toString()) != 0) {
            try {
                map.put("key", appConfiguration.getTencentKey2());
                String str = HttpRequest.get(appConfiguration.getQqApiUrl() + "location/v1/ip", map, true).body();
                result = (Map) Json.fromJson(str);
            } catch (Exception e) {
                System.out.println("获取地理位置异常" + e);
                logger.error("获取地理位置异常", e);
            }
        }
        if (result == null || Integer.valueOf(result.get("status").toString()) != 0) {
            try {
                map.put("key", appConfiguration.getTencentKey3());
                String str = HttpRequest.get(appConfiguration.getQqApiUrl() + "location/v1/ip").form(map).body();
                result = (Map) Json.fromJson(str);
            } catch (Exception e) {
                System.out.println("获取地理位置异常" + e);
                logger.error("获取地理位置异常", e);
            }
        }
        if (Integer.valueOf(result.get("status").toString()) == 0) {
            Map resultData = (Map) result.get("result");
            String lat = String.valueOf(Mapl.cell(resultData, "location.lat"));
            String lng = String.valueOf(Mapl.cell(resultData, "location.lng"));
            String city = (String) Mapl.cell(resultData, "ad_info.city");
            city = city.replace("市", "");
            QueryWrapper<PosCity> wrapper = new QueryWrapper<>();
            wrapper.eq("name", city);
            PosCity one = posCityService.getOne(wrapper);
            one.setLatitude(lat);
            one.setLongitude(lng);
            return one;
        }
        return null;
    }

    /**
     * 根据城市、关键字搜索地址
     */
    //@Cacheable(value = Cache.APPLICATION, key = "#root.targetClass.simpleName+':'+#cityName+'-'+#keyword")
    public List searchPlace(String cityName, String keyword) {
        logger.info("获取地址信息:{}，{}", cityName, keyword);
        Map<String, String> params = Maps.newHashMap();
        params.put("key", appConfiguration.getTencentKey());
        try {
            params.put("keyword", URLEncoder.encode(keyword, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        try {
            params.put("boundary", "region(" + URLEncoder.encode(cityName, "utf-8") + ",0)");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        params.put("page_size", "10");
        try {
            String str = HttpRequest.get(appConfiguration.getQqApiUrl() + "place/v1/search", params, true).body();
            System.out.println("返回的str：" + str);
            Map result = (Map) Json.fromJson(str);
            if (Integer.valueOf(result.get("status").toString()) == 0) {
                System.out.println("有结果：" + result.get("data"));
                return (List) result.get("data");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println("结果为空");
        return null;
    }

    /**
     * 根据经纬度坐标获取位置信息
     *
     * @param geohash
     * @return
     */
    //@Cacheable(value = Cache.APPLICATION, key = "#root.targetClass.simpleName+':'+#geohash")
    public Map pois(String geohash) {
        logger.info("获取地址信息:{}", geohash);
        Map<String, String> map = Maps.newHashMap();
        map.put("location", geohash);
        map.put("key", appConfiguration.getTencentKey());
        Map result = Maps.newHashMap();
        try {
            String str = HttpRequest.get(appConfiguration.getQqApiUrl() + "geocoder/v1", map, true).body();
            Map response = (Map) Json.fromJson(str);
            if ("0".equals(response.get("status").toString())) {
                result.put("address", Mapl.cell(response, "result.address"));
                result.put("city", Mapl.cell(response, "result.address_component.city"));
                result.put("name", Mapl.cell(response, "result.formatted_addresses.recommend"));
                result.put("latitude", Mapl.cell(response, "result.location.lat"));
                result.put("longitude", Mapl.cell(response, "result.location.lng"));
            } else {
                logger.error("获取地理位置信息失败:{}", str);
            }
        } catch (Exception e) {
            logger.error("获取地理位置异常", e);
        }
        return result;
    }

    /**
     * 根据起点、终点返回配送距离
     *
     * @param from
     * @param to
     * @return
     */
    public Map<String, String> getDistance(String from, String to) {
        Map<String, String> params = Maps.newHashMap(
                "ak", appConfiguration.getBaiduKey(),
                "output", "json",
                "origins", from,
                "destinations", to
        );
        try {
            //使用百度地图api获取距离值：
            //routematrix/v2/riding 骑行
            //routematrix/v2/driving 开车
            //routematrix/v2/walking 步行
            String str = HttpRequest.get(appConfiguration.getQqApiUrl() + "routematrix/v2/riding", params, true).body();
            Map response = (Map) Json.fromJson(str);
            if ("0".equals(response.get("status").toString())) {
                Map result = Maps.newHashMap(
                        "distance", Mapl.cell(response, "result[0].distance.text"),
                        "duration", Mapl.cell(response, "result[0].duration.text")
                );
                return result;
            }
        } catch (Exception e) {
            logger.error("通过百度获取配送距离失败", e);
        }
        return null;
    }
}
